﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace AviationSimulator.UDP
{
    class Receiver : IDisposable
    {
        private IPEndPoint _localIpAddress;
        private UdpClient _udpClient;

        public Receiver()
        {
            _localIpAddress = new IPEndPoint(IPAddress.Parse(Properties.Settings.Default.LocalIP),
                                       Properties.Settings.Default.LocalPort);
            _udpClient = new UdpClient(_localIpAddress);
        }

        public Datagram ReceiveDatagram(string ipAddress, int port)
        {
            var remoteEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);

            var result = new Datagram();

            if (_udpClient != null & remoteEndPoint != null)
            {
                try
                {
                    var rawDatagram = _udpClient.Receive(ref remoteEndPoint);

                    result.InitializeDatagram(rawDatagram);
                }
                catch (SocketException sex)
                {
                    //throw sex;  
                }
                catch (Exception ex)
                {

                    //throw ex;
                }
            }
            else
            {
                throw new ArgumentNullException("UDPClient, IPEndPoint", "not initialized");
            }

            return result;
        }

        public void Dispose()
        {
            try
            {
                _udpClient.Close();
            }
            catch (Exception)
            {
                
                throw;
            }
            
        }
    }
}
